package com.whosly.disclosure.early.handler.autoconfig.registrar;

import com.whosly.api.autoconfigure.holder.AnnotationMapsHolder;
import com.whosly.disclosure.early.handler.autoconfig.annotation.EnableAutoDisclosureEarly;
import com.whosly.disclosure.early.handler.autoconfig.data.DisclosureConfigData;
import org.slf4j.event.Level;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

public class DisclosureEarlyConfigRegistrar implements ImportBeanDefinitionRegistrar {

    public static final String BEAN_NAME = "disclosureEarlyConfigRegistrar";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        getAnnotationVal(importingClassMetadata);
    }

    private AnnotationMapsHolder getAnnotationVal(AnnotationMetadata metadata) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(
                metadata.getAnnotationAttributes(EnableAutoDisclosureEarly.class.getName()));

        AnnotationMapsHolder<DisclosureConfigData> holder = AnnotationMapsHolder.INSTANCE(BEAN_NAME);
        holder.set(assemblyData(attributes));

        return holder;
    }

    private DisclosureConfigData assemblyData(AnnotationAttributes annotationAttributes) {
        boolean enabled = annotationAttributes.getBoolean("enabled");
        Level level = annotationAttributes.getEnum("level");

        DisclosureConfigData configData = DisclosureConfigData.builder()
                .enabled(enabled)
                .level(level)
                .build();

        return configData;
    }


}
